package com.se.xb.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import com.alibaba.fastjson.JSON;
import com.se.xb.entity.User;
import com.se.xb.entity.dto.PageResult;
import com.se.xb.entity.dto.Result;
import com.se.xb.entity.dto.SearchDto;
import com.se.xb.entity.dto.UserDto;
import com.se.xb.service.UserService;
import com.se.xb.utils.FileUploadUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;


/**
 * @author 十里坡
 * @date 2020/5/27 16:05
 * @description: 用户控制器
 * @version: 1.0
 */
@WebServlet("/user/*")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 5, // 5MB
        maxFileSize = 1024 * 1024 * 50, // 50MB
        maxRequestSize = 1024 * 1024 * 100 // 100MB
)
public class UserServlet extends BaseServlet {
    private static final Logger logger = Logger.getLogger(UserServlet.class.getName());
    UserService userService = new UserService();

    public void getUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            response.getWriter().write(JSON.toJSONString(Result.error("未登录")));
            return;
        }
        response.getWriter().write(JSON.toJSONString(Result.success("免密登录")));
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String username = request.getParameter("form-username");
        String password = request.getParameter("form-password");
        String checkCode = request.getParameter("checkCode");
        HttpSession session = request.getSession();
        Object checkCode1 = session.getAttribute("sessionCode");
        if (checkCode1 == null || !checkCode1.equals(checkCode)) {
            response.getWriter().write(JSON.toJSONString(Result.error("验证码错误")));
            return;
        }
        Integer login = userService.login(username, password);
        if (login == 0) {
            response.getWriter().write(JSON.toJSONString(Result.error("用户名不存在")));
            return;
        } else if (login == 1) {
            response.getWriter().write(JSON.toJSONString(Result.error("密码错误")));
            return;
        } else if (login == 2) {
            session.setAttribute("user", userService.getUserByUsername(username));
            // 设置 Cookie
            Cookie cookie = new Cookie("username", username);
            cookie.setPath("/");
            // 设置 Cookie 有效期为 7 天
            cookie.setMaxAge(60 * 60 * 24 * 7);
            // 设置 HttpOnly 属性
            cookie.setHttpOnly(true);
            // 设置 Secure 属性
            cookie.setSecure(request.isSecure());
            response.addCookie(cookie);
            response.getWriter().write(JSON.toJSONString(Result.success()));
            return;
        } else {
            response.getWriter().write(JSON.toJSONString(Result.error("未知错误")));
            return;
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("form-username");
        String password = request.getParameter("form-password");
        String email = request.getParameter("form-email");
        String parameter = request.getParameter("form-phone");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(parameter);
        try {
            userService.register(user);
        } catch (SQLException e) {
            response.getWriter().write(JSON.toJSONString(Result.error("注册失败")));
        }
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从会话中移除用户信息
        request.getSession().removeAttribute("user");

        // 获取请求中的所有 Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 检查并删除与登录相关的 Cookie
                if ("username".equals(cookie.getName()) || "token".equals(cookie.getName()) || "session_id".equals(cookie.getName())) {
                    cookie.setValue("");
                    cookie.setMaxAge(0); // 设置 Cookie 的最大存活时间为 0，使其立即失效
                    cookie.setPath("/"); // 确保路径与设置时一致
                    response.addCookie(cookie); // 将修改后的 Cookie 添加到响应中
                }
            }
        }
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }

    public void checkUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User userByUsername = userService.getUserByUsername(request.getParameter("username"));
        if (userByUsername == null) {
            response.getWriter().write(JSON.toJSONString(Result.success()));
        } else {
            response.getWriter().write(JSON.toJSONString(Result.error("用户名已存在")));
        }
    }

    public void checkEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User email = userService.getUserByEmail(request.getParameter("email"));
        if (email == null) {
            response.getWriter().write(JSON.toJSONString(Result.success()));
        } else {
            response.getWriter().write(JSON.toJSONString(Result.error("邮箱已存在")));
        }
    }

    public void getCurrentUserDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        User userByUsername = userService.getUserByUsername(user.getUsername());
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userByUsername, userDto);
        Integer focusCount = userService.getFocusCount(userByUsername.getId());
        userDto.setFocusCount(focusCount);
        if (user == null) {
            response.getWriter().write(JSON.toJSONString(Result.error("未登录")));
        } else {
            response.getWriter().write(JSON.toJSONString(Result.success(userDto)));
        }
    }

    public void getUserDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Long userId =Long.valueOf(request.getParameter("userId"));
        User userById = userService.getUserById(userId);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(userById, userDto);
        Integer focusCount = userService.getFocusCount(userById.getId());
        userDto.setFocusCount(focusCount);
        response.getWriter().write(JSON.toJSONString(Result.success(userDto)));
    }

    public void updateCurrentUserDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        String parameter1 = request.getParameter("realName");
        user.setRealName(request.getParameter("realName"));
        String parameter = request.getParameter("gender");
        user.setGender(request.getParameter("gender"));
        String age = request.getParameter("age");
        user.setAge(Long.valueOf(request.getParameter("age")));
        user.setPhone(request.getParameter("phone"));
        user.setInfo(request.getParameter("info"));
        user.setIsSecret(request.getParameter("isSecret"));
        user.setPic(request.getParameter("pic"));
        user.setDeptName(request.getParameter("deptName"));
        try {
            userService.updateCurrentUserDetail(user);
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error("更新失败")));
        }
        response.getWriter().write(JSON.toJSONString(Result.success()));
    }

    public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        try {
            Part pic = request.getPart("pic");
            if (pic.getSize() > 0) {
                String fileName = pic.getSubmittedFileName();
                byte[] bytes = IOUtils.toByteArray(pic.getInputStream());
                String upload = FileUploadUtils.upload(fileName, bytes);
                String path = request.getRealPath(fileName);
                if (upload != null) {
                    response.getWriter().write(JSON.toJSONString(Result.success(upload)));
                } else {
                    response.getWriter().write(JSON.toJSONString(Result.error("上传失败")));
                }
            }
        } catch (IOException e) {
            response.getWriter().write(JSON.toJSONString(Result.error("文件读取失败")));
        } catch (ServletException e) {
            response.getWriter().write(JSON.toJSONString(Result.error("Servlet 异常")));
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error("未知错误")));
        }
    }

    public void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        SearchDto<String> stringSearchDto = new SearchDto<>(new ArrayList<>(), 1);
        stringSearchDto.setCurrentPage(Integer.valueOf(request.getParameter("page")));
        ArrayList<String> queryList = stringSearchDto.getQueryList();
        queryList.add(request.getParameter("name"));
        PageResult<User> userList = userService.getUserList(stringSearchDto);
        if (userList != null) {
            response.getWriter().write(JSON.toJSONString(Result.success(userList)));
        } else {
            response.getWriter().write(JSON.toJSONString(Result.error("获取失败")));
        }
    }

    public void focus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        try {
            userService.focus(user.getId(), Long.valueOf(request.getParameter("userId")));
            response.getWriter().write(JSON.toJSONString(Result.success()));
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error("关注失败")));
        }
    }

    public void unfocus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        try {
            userService.unfocus(user.getId(), Long.valueOf(request.getParameter("userId")));
            response.getWriter().write(JSON.toJSONString(Result.success()));
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error("取消关注失败")));
        }
    }

    public void getFocusList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        User user = (User) request.getSession().getAttribute("user");
        SearchDto<String> objectSearchDto = new SearchDto<>(new ArrayList<>(), 1);
        objectSearchDto.setCurrentPage(Integer.valueOf(request.getParameter("page")));
        ArrayList<String> queryList = objectSearchDto.getQueryList();
        queryList.add(String.valueOf(user.getId()));
        try {
            PageResult<User> focusList = userService.getFocusList(objectSearchDto);
            response.getWriter().write(JSON.toJSONString(Result.success(focusList)));
        } catch (Exception e) {
            response.getWriter().write(JSON.toJSONString(Result.error("获取失败")));
        }
    }

    

}
